<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商户" prop="merchantId">
        <el-select v-model="queryParams.merchantId"   size="small" placeholder="请选择所属商家" @keyup.enter.native="handleQuery">
          <el-option v-for="merchant in merchantList"
                     :key="merchant.deptId"
                     :label="merchant.deptName"
                     :value="merchant.deptId"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table
      ref="mytable"
      :data="table_data"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="radio" type="index" width="50"></el-table-column>
      <el-table-column v-if="selection" type="selection" width="55"></el-table-column>
      <el-table-column
        align="center"
        v-for="(item,index,key) in table_columns"
        :item="item"
        :key="key"
        :index="index"
        :label="item.label"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.edit && item.prop=='prizeIndex'">{{scope.row[item.prop]}}</span>
          <el-input
            v-if=" scope.row.edit && item.prop!='prizeName'&& item.prop!='prizeIndex'"
            size="small"
            v-model="scope.row[item.prop]"
            :placeholder="'请输入'+item.label"
          ></el-input>

          <el-select v-model="scope.row[item.prop]" v-if="item.prop=='prizeName'" placeholder="请选择优惠券" @change="getCouponList">
            <el-option v-for="coupon in couponList"
                       :key="coupon.id"
                       :label="coupon.title"
                       :value="coupon.id"/>
          </el-select>

          <span v-if="  !scope.row.edit  && item.prop!='prizeName'">{{scope.row[item.prop]}}</span>
        </template>
      </el-table-column>
    </el-table>
    <el-row :gutter="10" style="margin-top: 15px">
      <el-col :span="24" style="text-align: center;">
        <el-button
          size="mini"
          type="primary"
          @click="handleSave"
        >保存</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
    import {listPrize, getPrize, delPrize, addPrize, updatePrize, exportPrize} from "@/api/prize/prize";
    import {listCoupon} from "@/api/merchant/coupon";
    import {listDept} from "@/api/system/dept";
    export default {
        name: "Prize",
        data() {
            return {
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 抽奖奖品表格数据
                prizeList: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    merchantId: null,
                },
                // 表单参数
                form: {},
                // 表单校验
                rules: {
                    merchantId: [
                        {required: true, message: "商户不能为空", trigger: "blur"}
                    ],
                    prizeIndex: [
                        {required: true, message: "奖品序号不能为空", trigger: "blur"}
                    ],
                    prizeName: [
                        {required: true, message: "奖品名称不能为空", trigger: "blur"}
                    ],
                    stock: [
                        {required: true, message: "库存不能为空", trigger: "blur"}
                    ],
                    probability: [
                        {required: true, message: "概率，小于1的小数不能为空", trigger: "blur"}
                    ]
                },
                new_date_json: {}, //数据结构
                multipleSelection: [], //复选框，数据
                is_edit: true, //是否可编辑
                is_delete: true, //是否可删除
                selection: true, //是否需要复选框
                radio: false, //单选变色
                space_color: true, //隔行变色
                //表头信息
                table_columns: [
                    {
                        prop: "prizeIndex",
                        label: "位置",
                        width: "150"
                    },
                    {
                        prop: "prizeItem",
                        label: "奖项",
                        width: "150"
                    },
                    {
                        prop: "prizeName",
                        label: "奖品",
                        width: "150"
                    },
                    {
                        prop: "stock",
                        label: "库存",
                        width: ""
                    },
                    {
                        prop: "probability",
                        label: "中奖概率(2位小数)",
                        width: "150"
                    },
                ],
                //表格数据
                table_data: [
                    // {
                    //   date: "2016-05-03",
                    //   name: "王小虎",
                    //   province: "上海",
                    //   city: "普陀区",
                    //   address: "上海市普陀区金沙江路 1518 弄",
                    //   zip: 200333,
                    //   sex: 18
                    // },
                    // {
                    //   date: "2016-05-02",
                    //   sex: 18,
                    //   name: "王小虎",
                    //   province: "上海",
                    //   city: "普陀区",
                    //   address: "上海市普陀区金沙江路 1518 弄",
                    //   zip: 200333
                    // },
                    // {
                    //   date: "2016-05-04",
                    //   name: "王小虎",
                    //   sex: 18,
                    //   province: "上海",
                    //   city: "普陀区",
                    //   address: "上海市普陀区金沙江路 1518 弄",
                    //   zip: 200333
                    // }
                ],
                //优惠券列表
                couponList: [],
                // 商户列表
                merchantList: [],
            };
        },
        created() {
            this.getMerchantList();
        },
        mounted: function() {
            // this.initEditAttribute();
            //确保方法在页面渲染后调用
            this.$nextTick(function() {
                /////方法
                this.tableRowClassName();
            });

        },
        watch: {
            space_color: function() {
                //监听数据变化
                this.$nextTick(function() {
                    /////方法
                    this.tableRowClassName();
                });
            },
            table_data: function() {
                //监听数据变化f
                this.$nextTick(function() {
                    /////方法
                    this.tableRowClassName();
                });
            }
        },
        methods: {
            /** 查询抽奖奖品列表 */
            getList() {
                this.loading = true;
                listPrize(this.queryParams).then(response => {
                    this.loading = false;

                    let prizeList = response.rows;
                    if(prizeList==null||prizeList.length==0){
                        this.initAddData();
                    }else{
                        for(let i = 0;i<prizeList.length;i++){
                            let prize = prizeList[i];
                            prize.edit = true;

                        }
                        this.table_data=prizeList;
                    }

                });
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            initAddData(){
                var addDataJson = [
                    {
                        merchantId:this.queryParams.merchantId,
                        prizeIndex: 0,
                        prizeItem: "谢谢参与",
                        prizeName: "",
                        stock: 0,
                        probability: 0.80,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:this.queryParams.merchantId,
                        prizeIndex: 1,
                        prizeItem: "一等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:this.queryParams.merchantId,
                        prizeIndex: 2,
                        prizeItem: "二等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:this.queryParams.merchantId,
                        prizeIndex: 3,
                        prizeItem: "三等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:this.queryParams.merchantId,
                        prizeIndex: 4,
                        prizeItem: "一等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:this.queryParams.merchantId,
                        prizeIndex: 5,
                        prizeItem: "二等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:this.queryParams.merchantId,
                        prizeIndex: 6,
                        prizeItem: "三等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:this.queryParams.merchantId,
                        prizeIndex: 7,
                        prizeItem: "特等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    }
                ];

                this.table_data=addDataJson;
            },
            // 表单重置
            reset() {
                this.form = {
                    id: null,
                    merchantId: null,
                    prizeIndex: null,
                    prizeName: null,
                    stock: null,
                    probability: null
                };
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
                this.getCouponList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.id)
                this.single = selection.length !== 1
                this.multiple = !selection.length
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();

                if(!this.queryParams.merchantId){
                    this.msgError("请先选择商家进行搜索");
                    return false;
                }
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                const id = row.id || this.ids
                getPrize(id).then(response => {
                    this.form = response.data;
                    this.open = true;
                    this.title = "修改抽奖奖品";
                });
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.id != null) {
                            updatePrize(this.form).then(response => {
                                this.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            });
                        } else {
                            addPrize(this.form).then(response => {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            });
                        }
                    }
                });
            },

//隔行变色
            tableRowClassName() {
                //选取DOM节点
                var trs = this.$refs.mytable.$el
                    .getElementsByTagName("tbody")[0]
                    .getElementsByTagName("tr");
                for (var i in trs) {
                    if (i % 2 == 0) {
                        //当隔行变色未true时改变颜色
                        if (this.space_color) {
                            trs[i].style.backgroundColor = "#f0f9eb";
                        } else {
                            trs[i].style.backgroundColor = "";
                        }
                    }
                }
            },

            //多选框
            handleSelectionChange(val) {
                this.multipleSelection = val;
                console.log("selection:", this.multipleSelection);
            },
            //编辑
            handleEdit(index, row) {
                console.log(index, row);
                row.edit = true;
            },
            //删除
            handleDelete(index, row) {
                console.log(index, row);

                this.table_data.splice(index, 1);

                this.$message({
                    message: "删除成功！",
                    type: "success"
                });
            },
            //保存
            handleSave() {

                console.log(this.table_data);
                let prizeList = this.table_data;

                for(let i=0;i<prizeList.length;i++){
                    let prize = prizeList[i];
                    if(prize.id != null){
                        updatePrize(prize).then(response => {
                            this.msgSuccess("修改成功");
                        });
                    }else{
                        addPrize(prize).then(response => {
                            this.msgSuccess("新增成功");
                            prize.id = response.data.id;
                            console.log(prize);
                            delete this.table_data[index].add;
                        });
                    }
                }
            },

            //初始化编辑属性
            initEditAttribute() {
                var self = this;
                var edit = self.edit;

                var dataArray = [
                    {
                        merchantId:self.queryParams.merchantId,
                        prizeIndex: 0,
                        prizeItem: "谢谢参与",
                        prizeName: "谢谢参与",
                        stock: 0,
                        probability: 0.80,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:self.queryParams.merchantId,
                        prizeIndex: 1,
                        prizeItem: "一等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:self.queryParams.merchantId,
                        prizeIndex: 2,
                        prizeItem: "二等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:self.queryParams.merchantId,
                        prizeIndex: 3,
                        prizeItem: "三等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:self.queryParams.merchantId,
                        prizeIndex: 4,
                        prizeItem: "一等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:self.queryParams.merchantId,
                        prizeIndex: 5,
                        prizeItem: "二等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:self.queryParams.merchantId,
                        prizeIndex: 6,
                        prizeItem: "三等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    },
                    {
                        merchantId:self.queryParams.merchantId,
                        prizeIndex: 7,
                        prizeItem: "特等奖",
                        prizeName: "",
                        stock: 0,
                        probability: 0,
                        edit:true,
                        add:true
                    }
                ];

                if (dataArray.length > 0) {
                    //添加编辑事件
                    for (var index in dataArray) {
                        dataArray[index]["edit"] = false;
                        this.table_data.push(dataArray[index]);
                    }

                    if (Object.keys(this.new_date_json).length === 0) {
                        //新增时，初始化数据结构
                        this.initAddDataJson(dataArray[0]);
                    }
                }
                console.log("this.tableData:", this.table_data);
            },
            initAddDataJson(dataArray) {
                //新增时，初始化数据结构
                var dataJson = dataArray;
                var newDateJson = {};
                for (var key in dataJson) {
                    if (key === "edit") {
                        newDateJson[key] = "true";
                    } else {
                        newDateJson[key] = "";
                    }
                }
                newDateJson["add"] = true;
                this.new_date_json = newDateJson;
            },
            /**根据商家查询优惠券*/
            getCouponList() {
                this.loading = true;
                listCoupon(this.queryParams).then(response => {
                    this.couponList = response.rows;
                    this.couponList.push({id:-1,title:'谢谢参与'});
                    this.loading = false;
                });
            },
            /** 查询商户列表 */
            getMerchantList() {
                this.loading = true;
                listDept({deptType: 2}).then(response => {
                    this.merchantList = response.data;
                    this.loading = false;
                });
            },
        }
    };
</script>
